<template>

  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption"
                       :data="treeData"
                       :loading="loadingTree"
                       @save="saveType"
                       @node-click="nodeClick">
            </avue-tree>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <el-collapse class="avue-group" v-model="activeName" accordion>
          <el-collapse-item name="1">

            <template slot="title">
              <i class="el-icon-s-management avue-group__icon"></i>
              <h1 class="avue-group__title">字典类型信息</h1>

              <el-button :loading="saveTypeLoading" v-if="showBtn && (validatenull(permission.editCodeShow)?false:permission.editCodeShow)" type="primary" size="small" icon="el-icon-edit" @click="updateType($event)" style="margin-left: 20px;">{{btnText}}</el-button>
              <el-button v-if="showBtn && (validatenull(permission.delCodeShow)?false:permission.delCodeShow) && (oldDictType.delEnabled === 'Y')" type="danger" size="small" icon="el-icon-delete" @click="deleteType($event)" style="margin-left: 20px;">删 除</el-button>
            </template>

            <avue-form ref="form" v-model="dictType" :option="formOption" @submit="submitDictType">
            </avue-form>
          </el-collapse-item>
        </el-collapse>
      </basic-container>
      <basic-container>
        <avue-crud v-bind="bindVal"
                   v-on="onEvent"
                   :page.sync="page"
                   :before-close="beforeClose"
                   @tree-load="treeLoad"
                   v-model="form">

          <template slot="menuLeft">
            <el-button type="danger"
                       v-if="!validatenull(oldDictType.id) && (validatenull(permission.delCodeShow)?false:permission.delCodeShow)"
                       icon="el-icon-delete"
                       size="small"
                       @click.stop="deletes()">批量删除
            </el-button>
          </template>

          <template slot="menu"
                    slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-circle-plus-outline"
                       v-if="(oldDictType.isTree === 1) && (validatenull(permission.addCodeShow)?false:permission.addCodeShow)"
                       @click.stop="handleAdd(scope.row,scope.index)"
                       size="small">新增子项
            </el-button>
          </template>

          <template slot="code" slot-scope="scope">
            <el-tag>{{scope.row.code}}</el-tag>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>

</template>

<script>
import { dictTypeTree, getDictType, addType, updateType, delType, listDictChildList } from '@/api/system/dict'
import {mapGetters} from "vuex";
import {validatenull} from "@/util/validate";
export default window.$crudCommon({
  computed: {
    ...mapGetters(["isShowTenantCode"]),
    btnText() {
      return this.detail ? '编 辑' : '保 存'
    },
    formOption() {
      return {
        detail: this.detail,
        menuBtn: false,
        labelWidth: 150,
          column: [
            {
              label: "字典类型名称",
              prop: "dictTypeName",
              rules: [{
                required: true,
                message: "请输入类型编码",
                trigger: "blur"
              }]
            },
            {
              label: "字典类型编码",
              prop: "dictTypeCode",
              tip: '',
              rules: [{
                required: true,
                message: "请输入类型编码",
                trigger: "blur"
              }]
            },
            {
              label: "上级字典类型",
              type: "tree",
              prop: "parentId",
              dataType: 'string',
              display: !this.detail,
              dicData: this.treeData,
              props: {
                label: "title",
                value: 'id',
              }
            },
            {
              label: "排序",
              display: !this.detail,
              type: 'number',
              precision: 0,
              prop: "sortNum"
            },
            {
              label: "允许删除",
              prop: "delEnabled",
              type: 'switch',
              dataType: 'string',
              display: !this.detail,
              dicUrl: window.urllist.dictUrl + 'YN',
              value: "Y",
              props: {
                label: "name",
                value: "code"
              },
              rules: [{
                required: true,
                message: "请选择是否允许删除",
                trigger: "blur"
              }]
            },
            {
              label: "树形结构",
              prop: "isTree",
              display: !this.detail,
              dataType: 'number',
              type: 'switch',
              value: 0,
              dicUrl: window.urllist.dictUrl + 'YN01',
              props: {
                label: "name",
                value: "code"
              },
              rules: [{
                required: true,
                message: "请选择是否树形结构",
                trigger: "blur"
              }]
            },
            {
              label: "所属租户",
              prop: "tenantCode",
              placeholder:' ',
              row: true,
              span: 24,
              type: 'select',
              dicUrl: window.urllist.tenantSelectors,
              display: this.isShowTenantCode && this.detail,
              props: {
                label: 'tenant_name',
                value: 'tenant_code'
              }
            },
            {
              label: "备注",
              type: 'textarea',
              row: true,
              minRows: 1.5,
              span: 24,
              prop: "note"
            }
          ]
      }
    },
    treeOption(){
      return {
        nodeKey: 'key',
        menu: false,
        addBtn: (validatenull(this.permission.addTypeCodeShow)?false:this.permission.addTypeCodeShow),
        props: {
          labelText: '字典类型名称',
          label: 'title',
          value: 'key'
        },
        formOption: {
          labelWidth: 120,
          clearExclude: ['delEnabled', 'isTree'],
          column: [
            {
              label: "字典类型编码",
              prop: "dictTypeCode",
              rules: [{
                required: true,
                message: "请输入类型编码",
                trigger: "blur"
              }]
            },
            {
              label: "上级字典类型",
              type: "tree",
              prop: "parentId",
              dicData: this.treeData,
              props: {
                label: "title",
                value: 'id',
              }
            },
            {
              label: "排序",
              type: 'number',
              precision: 0,
              prop: "sortNum"
            },
            {
              label: "允许删除",
              prop: "delEnabled",
              type: 'switch',
              dataType: 'string',
              dicUrl: window.urllist.dictUrl + 'YN',
              value: "Y",
              props: {
                label: "name",
                value: "code"
              },
              rules: [{
                required: true,
                message: "请选择是否允许删除",
                trigger: "blur"
              }]
            },
            {
              label: "树形结构",
              prop: "isTree",
              type: 'switch',
              value: 0,
              dicUrl: window.urllist.dictUrl + 'YN01',
              props: {
                label: "name",
                value: "code"
              },
              rules: [{
                required: true,
                message: "请选择是否树形结构",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              type: 'textarea',
              row: true,
              span: 24,
              prop: "note"
            }
          ]
        }
      }
    }
  },
  data () {
    return {
      detail: true,
      showBtn: false,
      activeName: [],
      loadingTree: true,
      saveTypeLoading: false,
      treeData: [],
      dictType: {},
      oldDictType: {},
    }
  },
  created () {
    this.initTree();
  },
  watch: {
    'activeName' (activeName){
      if (activeName.length > 0){
        this.showBtn = true;
      }else{
        this.showBtn = false;
        this.detail = true;
        this.dictType = this.oldDictType;
      }
    },
    'oldDictType.dictTypeCode'(code){
      this.params.dictTypeCode = code;
      this.page.currentPage = 1;
      this.getList();
    }
  },
  methods: {
    initTree(){
      this.loadingTree = true;
      dictTypeTree().then(res => {
        this.treeData = res.data.data;
        this.loadingTree = false;
      });
    },
    nodeClick(data){
      getDictType(data.id).then((res)=>{
        this.dictType = res.data.data;
        this.oldDictType = res.data.data;
        this.detail = true;
        this.activeName = ['1'];
      });
    },
    searchBefore(){
      if (!validatenull(this.dictType) && !validatenull(this.dictType.id)){
        this.params.dictTypeCode = this.dictType.dictTypeCode;
      }
    },
    saveType(parent,data,done,loading){
      addType({
        ...data,
        dictTypeName: data.title
      }).then((res)=>{
        if (res.data.status){
          this.initTree();
          this.$message.success("新增成功")
          done();
        }else{
          loading();
          this.$message.error(res.data.message);
        }
      }).catch(() => {
        loading();
      });
    },
    updateType(e){
      e.stopPropagation();

      if (validatenull(this.dictType.id)){
        this.$message.warning("请先在左侧树选择字典类型");
        return;
      }

      if (this.detail){
        this.detail = false;
        this.findObject(this.formOption.column,'dictTypeCode').tip = '修改 类型编码 需手动修改该“字典”被调用代码，请谨慎修改此值';
      }else {
        this.$refs.form.submit();
      }
    },
    submitDictType(form,done){
      this.saveTypeLoading = true;

      this.$refs.form.validate((vaild)=>{
        if (vaild){
          updateType(form).then((res)=>{
            done();
            this.saveTypeLoading = false;
            if (res.data.status){
              this.initTree();
              this.oldDictType = { ...form };
              this.$message.success("操作成功");
              this.detail = true;
            }else{
              this.$message.error(res.data.message);
            }
          }).catch(() => {
            done();
            this.saveTypeLoading = false;
          });
        }
      });
    },
    deleteType(e){
      e.stopPropagation();
      if (validatenull(this.dictType) || validatenull(this.dictType.id)){
        this.$message.warning("请先在左侧树选择字典类型");
        return;
      }

      this.$confirm("确定删除字典此类型?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delType(this.dictType.id).then(()=>{
          this.initTree();
          this.$message.success("删除成功");
          this.$refs.form.resetForm();
          this.oldDictType = {};
          this.dictType.id = "";
          this.activeName = [];
        });
      }).catch(()=>{});
    },
    listBefore(){
      if (validatenull(this.dictType) || validatenull(this.dictType.id)){
        this.params.dictTypeCode = '瞎写的目的是啥也不查出来';
      }
    },
    handleAdd(row) {
      this.$refs.crud.rowAdd();
      this.$refs.crud.value.parentId = row.id;
      this.$refs.crud.value.parentName = row.name;
      this.findObject(this.$refs.crud.option.column,"parentName").value = row.name;
    },
    beforeClose(done,type){
      done();
      if (type === 'add'){
        this.$refs.crud.value.parentId = '';
        this.$refs.crud.value.parentName = '';
        this.findObject(this.$refs.crud.option.column,"parentName").value = '';
      }
    },
    treeLoad(tree, treeNode, resolve){
      listDictChildList(tree.id).then((res)=>{
        resolve(res.data.data);
      });

    }
  }
}, {
  name: '/system/dict',
  res: (data) => {
    return {
      total: data.data.total,
      data: data.data.list
    }
  }
})
</script>

<style lang="scss" scoped>

.el-collapse{
  border-bottom: 0px solid #EBEEF5;
  border-top: 0px solid #EBEEF5;
}
</style>